<template>
  <div class="roster" ref="roster">
    <el-row>
      <el-col>
        <el-select @change="searchChange"
          v-model="keywordId"
          filterable
          remote
          reserve-keyword
					:clearable="true"
          placeholder="姓名或手机号"
          :remote-method="remoteKeyword"
          :loading="loading">
          <el-option
            v-for="item in selectCollection.search"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <el-button type="primary" @click="showAlert">添加员工</el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-table
        :data="list"
        stripe
        v-loading="tableLoading"
        header-row-class-name="table-header"
        :header-cell-style="tableHeaderObj"
        @row-click="toDetail"
        style="width: 100%">
        <el-table-column
          label="头像"
          width="120"
          align="center">
          <template slot-scope="scope">
            <img :src="scope.row.photo_url" alt="" style="width: 50px;height:50px;border-radius:50%;vertical-align: middle;">
          </template>
        </el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          align="center">
        </el-table-column>
        <el-table-column
          prop="job_num"
          label="工号"
					min-width="120"
          align="center">
        </el-table-column>
        <el-table-column
          prop="company_name"
          label="隶属公司"
          width="240"
          align="center">
        </el-table-column>
        <el-table-column
          prop="department_name"
          label="部门"
          width="120"
          align="center">
        </el-table-column>
        <el-table-column
          prop="position"
          label="职位"
          align="center">
        </el-table-column>
        <el-table-column
          prop="mobile"
          label="手机号"
          width="120"
          align="center">
        </el-table-column>
        <el-table-column
          label="入职时间"
          width="120"
          align="center">
          <template slot-scope="scope">
            <span>{{scope.row.entry_time | parseTime('{y}-{m}-{d}')}}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="emptype_text"
          label="员工类型"
          align="center">
        </el-table-column>
        <el-table-column
          prop="status_text"
          label="状态"
          align="center">
        </el-table-column>
      </el-table>
    </el-row>
    <el-row class="pager">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page['page']"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page['per-page']"
        layout="sizes, prev, pager, next, jumper"
        :total="totalPage">
      </el-pagination>
    </el-row>
    <!-- 添加员工 -->
      <el-col :span="12"  class="box-card" ref="alertWrap" v-if="addAlert">
        <el-form ref="form" :model="form" :rules="rules" label-width="85px" label-position="left">
          <el-card>
            <el-row class="card_header">
              <span>添加员工</span>
              <el-col :span="8" class="card_header_btn">
                <el-button type="primary" @click="saveBtn">保存</el-button>
                <el-button @click="addAlert=false">取消</el-button>
              </el-col>
            </el-row>
            <el-row class="item">
              <p>基础信息</p>
              <el-col :span="12">
                <el-form-item label="姓名" prop="base.name">
                  <el-input v-model="form.base.name" placeholder="请输入姓名"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工号">
                  <span style="color: #c0c4cc;">系统自动创建</span>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="隶属公司" prop="base.company">
                  <el-select @change="companyChoose"
                    v-model="form.base.company"
                    placeholder="请选择">
                    <el-option
                      v-for="item in selectCollection.company"
                      :key="item.id"
                      :label="item.company_name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="部门" prop="base.section">
                  <el-select
                    v-model="form.base.section"
                    placeholder="请选择">
                    <el-option
                      v-for="item in selectCollection.section"
                      :key="item.id"
                      :label="item.department_name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="职位" prop="base.job">
                  <el-input v-model="form.base.job" placeholder="请输入职位"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="手机号" prop="base.phone">
                  <el-input v-model="form.base.phone" placeholder="请输入手机号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12" class="date-icon">
                <el-form-item label="入职时间" prop="base.time">
                  <el-date-picker
                    prefix-icon="el-icon-date"
                    v-model="form.base.time"
                    align="right"
                    type="date"
                    @blur="baseTime"
                    placeholder="选择日期"
										:editable="false"
										:clearable="false"
                    :picker-options="picker.options1">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="item">
              <p>工作信息</p>
              <el-col :span="12">
                <el-form-item label="员工类型" prop="work.type">
                  <el-select
                    v-model="form.work.type"
                    placeholder="请选择">
                    <el-option
                      v-for="item in selectCollection.emptype"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="试用期" prop="work.try">
                  <el-select @change="trialChoose"
                    v-model="form.work.try"
                    placeholder="请选择">
                    <el-option
                      v-for="item in selectCollection.trial"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="员工状态" prop="work.status">
                  <el-select
                    v-model="form.work.status"
                    placeholder="请选择">
                    <el-option
                      v-for="item in selectCollection.employee_status"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" class="date-icon">
                <el-form-item label="转正日期" prop="work.end">
                  <el-date-picker
                    prefix-icon="el-icon-date"
                    v-model="form.work.end"
                    align="right"
                    type="date"
                    placeholder="选择日期"
										:editable="false"
                    :picker-options="picker.options2">
                  </el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row class="item">
              <p>合同信息</p>
              <el-col :span="12">
                <el-form-item label="合同类型" prop="contract.type">
                  <el-select
                    v-model="form.contract.type"
                    placeholder="请选择">
                    <el-option
                      v-for="item in selectCollection.contract_type"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="合同期限" prop="contract.time">
                  <el-select @change="contractChoose"
                    v-model="form.contract.time"
                    placeholder="请选择">
                    <el-option
                      v-for="item in selectCollection.contract_life"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" class="date-icon">
                <el-form-item class="width81" label="合同起始日" prop="contract.begin">
                  <el-date-picker
                    prefix-icon="el-icon-date"
                    v-model="form.contract.begin"
                    align="right"
                    type="date"
                    placeholder="选择日期"
                    @blur="beginTime"
										:editable="false"
                    :picker-options="picker.options3">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12" class="date-icon">
                <el-form-item class="width81" label="合同到期日" prop="contract.end">
                  <el-date-picker
                    prefix-icon="el-icon-date"
                    v-model="form.contract.end"
                    align="right"
                    type="date"
                    placeholder="选择日期"
										:editable="false"
                    :picker-options="picker.options4">
                  </el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-checkbox v-model="form.notify">通知该员工完善个人信息</el-checkbox>
              </el-col>
            </el-row>
          </el-card>
        </el-form>
      </el-col>
  </div>
</template>
<style scoped>
  .roster > .el-row {
    margin-bottom: 30px;
  }
  /* 文本框 */
  .inline-input {
    position: relative;
  }
  .inline-input >>> .el-input input {
    text-indent: 25px;
    color: #666;
  }
  .inline-input >>> .el-input i {
    position: absolute;
    top: 0;
    left: -200px;
  }
  /* 表格 */
  .el-table {
    text-align: center;
    border: 1px solid #dfe6ec;
    border-bottom: none;
    min-width: 1200px;
  }
  .el-table >>> .el-table__row{
    height: 75px;
  }
  .el-table >>> .el-table__body {
    cursor: pointer;
  }
  /* 分页 */
  .pager {
    text-align: center;
    margin-top: 20px;
  }
  .el-pager {
    font-weight: normal;
  }
  /* 添加员工 */
  .box-card {
    z-index: 2;
    position: absolute;
    top: 66px;
    right: 0;
    min-width: 745px;
    overflow: auto;
  }
  .box-card >>> .el-card .el-card__body {
    padding: 0;
  }
  .card_header {
    margin-bottom: 10px;
    padding: 50px 30px 0px;
  }
  .card_header span {
    float: left;
    font-weight: bold;
  }
  .card_header .card_header_btn {
    float: right;
  }
  .card_header_btn button {
    float: right;
    margin-left: 20px;
  }
  .item > p{
    margin: 0;
    font-size: 14px;
    padding: 16px 30px;
    background: #f5f7fa;
    font-weight: bold;
  }
  .item .el-col {
    padding: 20px 30px;
  }
  .item .el-col .el-form-item {
    margin-bottom: 0;
  }
  /* .date-icon >>> .el-input i {
    position: absolute;
    right: -210px;
    top: 0;
  } */
  .date-icon >>> .width81 .el-form-item__label {
    width: 81px!important;
  }
  .date-icon >>> .el-form-item .el-form-item__label {
    padding: 0;
  }
	.el-form .el-col >>> .el-select {
		width: 100%;
	}
	.el-form .el-date-editor.el-input {
		width: 100%!important;
	}
  /* card动画 */
  .slide-fade-enter-active, .slide-fade-leave-active {
    opacity: 0;
  }
  .slide-fade-enter, .slide-fade-leave-to {
    opacity: 1;
  }
</style>
<script>
import {getCompanySelect, getSectionSelect, getOtherSelect, getPositiveTime, getContractTime, addPerson, getPersonList, searchList} from '@/api/hr'
export default {
  data () {
    var checkPhone = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (value.length !== 11) {
        callback(new Error('手机号长度 11 个字符'))
      } else if (!(/^1[3456789]\d{9}$/.test(value))) {
        callback(new Error('手机号格式错误'))
      } else {
        callback()
      }
    }
    return {
      list: [],
      keywordId: '',
      loading: false,
      tableLoading: false,
      restaurants: [],
      addAlert: false,
      alertHeight: '',
      totalPage: null,
      page: {
        'per-page': 20,
        page: 1
      },
      tableHeaderObj: {
        'background-color': '#f5f7fa',
        'color': '#606266',
        'height': '68px'
      },
      selectCollection: {
        search: [],
        company: [],
        section: [],
        emptype: [],
        trial: [],
        employee_status: [],
        contract_type: [],
        contract_life: []
      },
      form: {
        base: {
          name: '',
          company: '',
          section: '',
          job: '',
          phone: '',
          time: ''
        },
        work: {
          type: '',
          try: '',
          status: '',
          end: ''
        },
        contract: {
          type: '',
          time: '',
          begin: '',
          end: ''
        },
        notify: true
      },
      rules: {
        base: {
          name: [
            { required: true, message: '请输入姓名', trigger: 'blur' },
            { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
          ],
          phone: [
            { required: true, validator: checkPhone, trigger: 'blur' }
          ],
          company: [
            { required: true, message: '请选择隶属公司', trigger: 'change' }
          ],
          section: [
            { required: true, message: '请选择部门', trigger: 'change' }
          ],
          job: [
            { required: true, message: '请输入职位', trigger: 'blur' },
            { min: 1, max: 5, message: '长度在 1 到 12 个字符', trigger: 'blur' }
          ],
          time: [
            { required: true, message: '请选择日期', trigger: 'change' }
          ]
        },
        work: {
          type: [
            { required: true, message: '请选择员工类型', trigger: 'change' }
          ],
          try: [
            { required: true, message: '请选择试用期', trigger: 'change' }
          ],
          status: [
            { required: true, message: '请选择员工状态', trigger: 'change' }
          ],
          end: [
            { required: true, message: '请选择转正日期', trigger: 'change' }
          ]
        },
        contract: {
          type: [
            { required: true, message: '请选择合同类型', trigger: 'change' }
          ],
          time: [
            { required: true, message: '请选择合同期限', trigger: 'change' }
          ],
          begin: [
            { required: true, message: '请选择合同起始日', trigger: 'change' }
          ],
          end: [
            { required: true, message: '请选择合同到期日', trigger: 'change' }
          ]
        }
      },
      picker: {
        options1: {
          disabledDate(time) {
          }
        },
        options2: {
          disabledDate(time) {
          }
        },
        options3: {
          disabledDate(time) {
          }
        },
        options4: {
          disabledDate(time) {
          }
        }
      }
    }
  },
  created() {
    this.initList()
    this.initFun()
  },
  methods: {
    initList() {
			this.tableLoading = true
      getPersonList(this.page).then((response) => {
        this.list = response.data.data
        this.tableLoading = false
        this.totalPage = response.data._meta.totalCount
      })
    },
    initFun() {
      getCompanySelect().then((response) => {
        this.selectCollection.company = response.data
      })
      getOtherSelect({type: 'emptype'}).then((response) => {
        this.selectCollection.emptype = response.data
      })
      getOtherSelect({type: 'trial'}).then((response) => {
        this.selectCollection.trial = response.data
      })
      getOtherSelect({type: 'employee_status'}).then((response) => {
        this.selectCollection.employee_status = response.data
      })
      getOtherSelect({type: 'contract_type'}).then((response) => {
        this.selectCollection.contract_type = response.data
      })
      getOtherSelect({type: 'contract_life'}).then((response) => {
        this.selectCollection.contract_life = response.data
      })
    },
    searchChange() {
      this.page.id = this.keywordId
			this.initList()
			this.selectCollection.search = []
    },
    companyChoose() {
      getSectionSelect({company_id: this.form.base.company}).then((response) => {
        this.selectCollection.section = response.data
      })
    },
    trialChoose() {
      if (this.form.base.time && this.form.work.try) {
        getPositiveTime({entry_time: this.form.base.time, trial: this.form.work.try}).then((response) => {
          this.form.work.end = response.data.positive_time
        })
      }
    },
    contractChoose() {
      if (this.form.contract.begin && this.form.contract.time) {
        getContractTime({contract_begin_time: this.form.contract.begin, contract_life: this.form.contract.time}).then((response) => {
          this.form.contract.end = response.data.contract_endline
        })
      }
    },
    createStateFilter(queryString) {
      return (state) => {
        return (state.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    saveBtn() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          const params = {
            username: this.form.base.name,
            company_id: this.form.base.company,
            department_id: this.form.base.section,
            position: this.form.base.job,
            mobile: this.form.base.phone,
            entry_time: this.form.base.time,
            emptype: this.form.work.type,
            trial: this.form.work.try,
            status: this.form.work.status,
            positive_time: this.form.work.end,
            contract_type: this.form.contract.type,
            contract_life: this.form.contract.time,
            contract_begin_time: this.form.contract.begin,
            contract_end_time: this.form.contract.end,
            notify: this.form.notify
          }
          addPerson(params).then((response) => {
            if (response.status === 200) {
              this.addAlert = false
              this.initList()
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    remoteKeyword(query) {
      if (query !== '') {
        this.loading = true
        setTimeout(() => {
          this.loading = false
          searchList({kw: query}).then((response) => {
						this.keywordId = ''
						this.selectCollection.search = []
            response.data.forEach((item, index) => {
              if (item.mobile) {
                this.selectCollection.search.splice(index, 0, { value: item.id, label: item.mobile })
              } else {
                this.selectCollection.search.splice(index, 0, { value: item.id, label: item.username })
              }
            })
            return this.selectCollection.search
          })
        }, 200)
      } else {
        this.selectCollection.search = []
      }
    },
    baseTime() {
      const _this = this
      _this.picker.options2 = {
        disabledDate(time) {
          return time.getTime() < new Date(_this.form.base.time).getTime()
        }
      }
      _this.trialChoose()
    },
    beginTime() {
      const _this = this
      _this.picker.options4 = {
        disabledDate(time) {
          return time.getTime() < new Date(_this.form.contract.begin).getTime()
        }
      }
      _this.contractChoose()
    },
    showAlert() {
      this.clearAlert()
      if (!this.addAlert) {
        this.addAlert = true
        setTimeout(() => {
          const winHeight = document.body.clientHeight
          const headerHeight = document.querySelector('.headerHeight').offsetHeight
          const alertHeight = winHeight - headerHeight
          document.querySelector('.box-card').style.height = alertHeight + 'px'
          document.querySelector('.box-card').style.maxHeight = alertHeight + 'px'
        }, 100)
      }
    },
    handleSizeChange(val) {
      this.page['per-page'] = val
      this.initList()
    },
    handleCurrentChange(val) {
			this.page.page = val
      this.initList()
    },
    toDetail(row) {
			this.$router.push('/hr/personal?id=' + row.id)
    },
		// 初始化添加员工弹框
		clearAlert() {
			this.form = {
				base: {
					name: '',
						company: '',
						section: '',
						job: '',
						phone: '',
						time: ''
				},
				work: {
					type: '',
					try: '',
					status: '',
					end: ''
				},
				contract: {
					type: '',
					time: '',
					begin: '',
					end: ''
				},
				notify: true
			}
		}
  },
  mounted() {
  }
}
</script>

